<template>
  <el-dialog
    title="线下还款审批"
    :visible.sync="isShowModel"
    :before-close="handleClose"
    :close-on-click-modal="false"
    @close="$emit('update:isShowDetail', false)"
    class="repayment">
    <el-form :model="repaymentInfo" :rules="rules" ref="repaymentInfo" label-width="140px" class="demo-dynamic">
       <el-form-item label="采购商名称：">
         {{dataInfo.enterpriseName}}
       </el-form-item>
      <el-form-item label="还款金额" prop="credit" required v-if="repaymentInfo.selectStatus == '1'" class="moneyShow">
        <el-input placeholder="请还款金额" v-model="repaymentInfo.credit" max="999999999">
          <template slot="append">元</template>
        </el-input>
        <el-button type="primary" @click.prevent="searchBillRepay">查询</el-button>
        <div>偿还本金：￥{{ moneyInfo.principal && moneyInfo.principal != 0 ? formatMoney.twoDecimal(moneyInfo.principal) : '0.00'}}&nbsp;&nbsp;偿还利息：{{ moneyInfo.interest && moneyInfo.interest != 0 ? formatMoney.twoDecimal(moneyInfo.interest) : '0.00'}} 违约金：{{ moneyInfo.penalty || moneyInfo.penalty == 0 ? formatMoney.twoDecimal(moneyInfo.penalty) : '0.00'}}</div>
      </el-form-item>
      <el-form-item prop="selectStatus">
        <el-radio v-model="repaymentInfo.selectStatus" label="1">通过</el-radio>
        <el-radio v-model="repaymentInfo.selectStatus" label="2">否决驳回</el-radio>
      </el-form-item>
      <el-form-item label="还款凭证录入：" v-if="repaymentInfo.selectStatus == '1'" required prop="proof">
        <el-row :gutter="10" >
          <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8" v-for="(img, index) in repaymentInfo.proof.split(',')" :key="index" v-if="repaymentInfo.proof" style="margin-bottom: 50px">
            <div class="imgArea">
              <viewer :images="repaymentInfo.proof ? repaymentInfo.proof.split(',') : []">
                <div>
                  <img :src="repaymentInfo.proof.split(',')[index]">
                </div>
              </viewer>
              <div class="operateBtn">
                <el-button size="small" type="text" @click="deleteOtherImg(index)">删除</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <div v-if="!repaymentInfo.proof || (repaymentInfo.proof && repaymentInfo.proof.split(',').length < 5)">
          <el-button type="primary" @click="showCropper">上传图片</el-button>
          <p>文件不能超过5MB</p>
        </div>
      </el-form-item>
      <el-form-item label="驳回原因：" v-if="repaymentInfo.selectStatus == '2'" required prop="reason">
        <el-input type="textarea" v-model="repaymentInfo.reason " placeholder="驳回原因（150字一下）" :autosize="{ minRows: 6, maxRows: 8}" max="150"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="repaymentInfo.selectStatus">
      <el-button @click="closeModel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
    <jxf-cropper
      :uploadUrl="upload"
      :isShowCropper.sync="isShowCropper"
      :tCropWidth="tCropWidth"
      :tCropHeight="tCropHeight"
      :dealImage.sync="dealImage"
      @getChangedImage="getChangeImage"
      :dataSize="5"></jxf-cropper>
  </el-dialog>
</template>

<script>
  import formatMoney from '@/assets/js/formatMoney'
    export default {
        name: "RepaymentApproval",
        props: {
          isShowDetail: {
            type: Boolean,
            default: false
          },
          dataInfo: {
            type: Object,
            default: () => {}
          }
        },
        data() {
          return {
            // 裁剪
            isShowCropper: false,
            tCropWidth: 800,
            tCropHeight: 800,
            dealImage: '',
            /***********/
            moneyInfo: {},
            fileList: [],
            formatMoney: formatMoney,
            rules: {
              credit: [
                { required: true, message: '还款金额不能为空', trigger: ['change', 'blur'] },
                { validator: validate.price2, trigger: ['change', 'blur'] }
              ],
              reason: [
                { required: true, message: '驳回原因不能为空', trigger: ['change', 'blur'] },
                { validator: validate.length150, trigger: ['change', 'blur'] }
              ],
              proof: [
                { required: true, message: '图片凭证不能为空', trigger: ['change', 'blur'] },
              ]
            },
            repaymentInfo: {
              proof: "",
              reason: "",
              credit: "",
              selectStatus: ""
            },
            header: {
              token: JSON.parse(window.localStorage.adminLogin).token
            } ,
            upload: apis.operate.advUpload ,
            isShowModel: this.isShowDetail
          }
        },
        methods: {
          /*******/
          showCropper() {
            this.dealImage = '';
            this.isShowCropper = true;
          },
          getChangeImage(val) {
            if(this.repaymentInfo.proof) {
              this.repaymentInfo.proof = this.repaymentInfo.proof + ',' + val;
            } else {
              this.repaymentInfo.proof = val
            }
          },
          /*******/

          deleteOtherImg(index) {
            let array = this.repaymentInfo.proof.split(',');
            if(this.repaymentInfo.proof && this.repaymentInfo.proof.split(',')) {
              array.splice(index, 1)
              this.repaymentInfo.proof = array.join(',')
            }
          },
          closeModel() {
            this.resetForm()
            this.$emit('update:isShowDetail', false)
          },
          resetForm() {
            this.$refs['repaymentInfo'].resetFields()
          },
          // 改变选择的状态
          changeStatus(e) {
            this.resetForm()
            e === this.repaymentInfo.selectStatus ? this.repaymentInfo.selectStatus = "" : this.repaymentInfo.selectStatus = e;
          },
          searchBillRepay() {
            let data = {
              billId: this.dataInfo.billId,
              repayCredit: this.repaymentInfo.credit ? this.repaymentInfo.credit : 0,
              repayType: this.dataInfo.repayType
            }
            ajax.post(apis.factory.billRepayDetail, data).then(res => {
              if(res.code === "10000000") {
                  this.moneyInfo = res.data
              } else {
                this.$message.error(res.message)
              }
            })
          },
          submitForm() {
            let data = {}
            this.$refs['repaymentInfo'].validate((valid) => {
                if (valid) {
                  if(this.repaymentInfo.selectStatus == '1') {
                    data = {
                      repayId: this.dataInfo.id,
                      credit: this.repaymentInfo.credit,
                      proof: this.repaymentInfo.proof
                    }
                    ajax.post(apis.factory.passRepay, data).then(res => {
                      if(res.code == "10000000") {
                        this.$message({
                          message: '审批通过！',
                          type: 'success'
                        });
                        this.$emit('fresh')
                        this.closeModel()
                      } else {
                        this.$message.error(res.message)
                      }
                    })
                  } else {
                    data = {
                      repayId: this.dataInfo.id,
                      reason: this.repaymentInfo.reason
                    }
                    ajax.post(apis.factory.rejectRepay, data).then(res => {
                      if(res.code == "10000000") {
                        this.$message({
                          message: '驳回成功！',
                          type: 'success'
                        });
                        this.$emit('fresh')
                        this.closeModel()
                      } else {
                        this.$message.error(res.message)
                      }
                    })
                  }
                }
            })
          },
          handleClose(done) {
            this.repaymentInfo = {
              proof: "",
              reason: "",
              credit: "",
              selectStatus: ""
            }
            this.resetForm()
            done()
          },
          handleRemove(file, fileList) {

          },
          beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
              this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isLt2M;
          },
          uploadSuccess(response, file, fileList) {
            if(response.code == "10000000") {
              // this.reviewInfo.proof = this.reviewInfo && this.reviewInfo.proof ? this.reviewInfo.proof.split(',').push(response.data.fileUrl).join(',') : response.data.fileUrl
              if(this.repaymentInfo.proof) {
                this.repaymentInfo.proof = this.repaymentInfo.proof + ',' + response.data.fileUrl;
              } else {
                this.repaymentInfo.proof = response.data.fileUrl
              }
            } else {
              this.$message.error(response.message)
            }
          },
        },
        watch: {
          isShowDetail(val) {
            this.isShowModel = val
          }
        }
    }
</script>

<style lang="scss">
.repayment {
  .el-dialog {
    width: 600px;
    .moneyShow {
      .el-input {
        width: 81%!important;
      }
    }
  }
  .imgArea {
    width: 120px;
    height: 120px;
    border: 1px solid #f2f2f2;
    img {
      margin: 5px;
      width: 110px;
      height: 110px;
    }
    .operateBtn {
      margin-top: -15px;
      padding: 0 5px;
      width: 110px;
      border: 1px solid #f2f2f2;
    }
  }
}

</style>
